#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "StdFile.h"

// void Print(ElementType value)
// {
//     char* content = (char*)value;
//     printf("%s\n", content);
// }

// void FreeStr(ElementType value)
// {
//     free(value);
// }

struct User
{
    char UserName[20];
    char Passwd[20];
};

static DList UserList;

struct User* CreateUser(const char* name, const char* passwd)
{
    struct User* user = (struct  User*)malloc(sizeof(struct User));
    if(user == NULL)
    {
        printf("malloc error!\n");
    }

    strcpy(user->UserName, name);
    strcpy(user->Passwd, passwd);
    return user;
}

void FreeUser(struct User* user)
{
    if(user != NULL)
    {
        free(user);
    }
}

void StrTok(ElementType element)
{
    char* str = (char*) element;
    char* userName = strtok(str, "=");
    char* password = strtok(NULL, "=");
    struct User* user = CreateUser(userName, password);
    DList_InsertTail(&UserList, user);
}

int login(const char* name, const char * passwd)
{
    struct DNode * TravelPoint = UserList.head;
    while(TravelPoint != NULL)
    {
        struct User* user = (struct User*)TravelPoint->data;

        if(strcmp(user->UserName, name) == 0 && strcmp(user->Passwd, passwd) == 0)
        {
                  return 1;
        }
        TravelPoint = TravelPoint->next;
    }
   return 0; 
}

void Print(ElementType element)
{
    struct User* user = (struct User*)element;
    printf("user : %s , passwd : %s\n", user->UserName, user->Passwd);
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("invalid number!\n");
        return 0;
    }

    DList_Init(&UserList);
    DList* list = GetLineFromFile("test.txt");
    DList_Travel(list, StrTok);
    DList_Travel(&UserList, Print);


    if(login(argv[1], argv[2]) == 1)
    {
        printf("login success!\n");
    }
    else
    {
        printf("login fail!\n");
    }



    return 0;
}